package com.zr.andealib.util;

import android.content.Context;
import android.util.Log;

import com.andea.lockuntils.LockUtils;
import com.zr.andealib.util.constant.AndeaConstant;

import org.greenrobot.eventbus.EventBus;


/**
 * @author WQJ
 * @create 2019/11/19
 * @desc:门锁操作类
 */
public class LockUtil {

    private Context context;

    private boolean initSuccess;
    private  int boxNum;
    private  int caseNo;

    public void init() {
        try {
            LockUtils.destroyLock();
            int ret = LockUtils.initLock(AndeaConstant.LOCK_TTY);
            if (ret == 1) {
                initSuccess = true;
            }
        } catch (Exception e) {
            EventBus.getDefault().post(new HardEvent("门锁初始化失败", AndeaConstant.CALL_LOCK_STATUS_ERROR));
        } catch (UnsatisfiedLinkError e) {
            EventBus.getDefault().post(new HardEvent("门锁初始化失败", AndeaConstant.CALL_LOCK_STATUS_ERROR));
        }
    }

    public void openDoor(Integer boxNum) {
        if (!LockUtils.isLockDevOpen()) {
            init();
        }
        changeBoxNum(boxNum);
//        0是开 1是关闭
        int ret = LockUtils.readLock(caseNo, this.boxNum, 200);
        if (ret == 0) {
            Log.e("task","柜门处于开启状态");
            EventBus.getDefault().post(new HardEvent("柜门处于开启状态", AndeaConstant.CALL_LOCK_STATUS_ERROR));
        } else {
            LockUtils.unlock(caseNo, this.boxNum);
            EventBus.getDefault().post(new HardEvent(boxNum, AndeaConstant.CALL_LOCK_STATUS_SUCCSES));
        }

    }

    public void openDoorWithoutCheck(Integer boxNum) {
        changeBoxNum(boxNum);
        int lockStatus = LockUtils.unlock(caseNo, this.boxNum);
        if (lockStatus == 1) {
            EventBus.getDefault().post(new HardEvent(boxNum, AndeaConstant.CALL_LOCK_STATUS_SUCCSES));
        } else {
            EventBus.getDefault().post(new HardEvent("箱门开启失败", AndeaConstant.CALL_LOCK_STATUS_ERROR));
        }
    }


    /**
     * 判断柜门是否开启
     *
     * @param boxNum
     * @return 开 true
     */
    public boolean isDoorOPen(Integer boxNum) {
        if (!LockUtils.isLockDevOpen()) {
            init();
        }
        changeBoxNum(boxNum);
        return LockUtils.readLock(caseNo, this.boxNum, 200) == 0;
    }


    public Integer readLock(Integer boxNum) {
        changeBoxNum(boxNum);
        return LockUtils.readLock(caseNo, this.boxNum);
    }
   private void changeBoxNum(Integer boxNum){
       if (boxNum <= 8) {
           caseNo = 1;
           this.boxNum = boxNum;
       } else if ( boxNum <= 16) {
           caseNo = 2;
           this.boxNum = boxNum - 8;
       } else {
           caseNo = 3;
           this.boxNum = boxNum - 16;
       }
   }

    public void destory() {
        if (initSuccess) {
            LockUtils.destroyLock();
            initSuccess = false;
        }
    }

}
